package com.lin.missyou.service;

import com.lin.missyou.core.LocalUser;
import com.lin.missyou.dto.RegisterDTO;
import com.lin.missyou.exception.http.ParameterException;
import com.lin.missyou.models.User;
import com.lin.missyou.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User getUserById(Long id) {
        return userRepository.findFirstById(id);
    }
    public void updateUserWxInfo(Map<String, Object> wxUser) {
        User user =this.getUserById(LocalUser.getUser().getId());
        user.setNickname(wxUser.get("nickName").toString());
        user.setWxProfile(wxUser);
        userRepository.save(user);
    }

    public User createDevUser(Long uid) {
        User newUser = User.builder().unifyUid(uid).build();
        userRepository.save(newUser);
        return newUser;
    }

    public void registerUserInfo(RegisterDTO registerInfo){
        User user = this.getUserById(LocalUser.getUser().getId());

        if(userRepository.countByAlipayAccount(registerInfo.getAlipayAccount())>0){
            throw new ParameterException(60000);
        }

        if(userRepository.countByQqNumber(registerInfo.getQqNumber())>0){
            throw new ParameterException(60001);
        }

        if(userRepository.countByNickname(registerInfo.getNickname())>0){
            throw new ParameterException(60002);
        }

        user.setNickname(registerInfo.getNickname());
        user.setMobile(registerInfo.getMobile());
        user.setDescription(registerInfo.getDescription());
        user.setAlipayAccount(registerInfo.getAlipayAccount());
        user.setAlipayName(registerInfo.getAlipayName());
        user.setSpeciality(registerInfo.getSpeciality());
        userRepository.save(user);
    }

    public User getUserByUnifyUid(Long uuid) {
        return userRepository.findByUnifyUid(uuid);
    }

}
